package net.sf.midollo.io.text;

import java.io.IOException;
import java.io.OutputStream;

public class Formatter {

  public static final int MAX_LONG_DIGITS = 19;

  protected final OutputStream os;
  protected final byte[] longBuffer;

  public Formatter(OutputStream os) throws IOException {
    this.os = os;
    this.longBuffer = new byte[MAX_LONG_DIGITS];
  }

  public void formatString(String value) throws IOException {
    int len = value.length();
    for (int idx = 0; idx < len; ++idx)
      this.os.write((byte)value.charAt(idx));
  }

  public void formatString(StringBuffer value) throws IOException {
    int len = value.length();
    for (int idx = 0; idx < len; ++idx)
      this.os.write((byte)value.charAt(idx));
  }

  public void formatInt(int value) throws IOException {
    formatLong(value);
  }

  public void formatLong(long value) throws IOException {
    int len = preformatLong(value);
    for (int idx = len - 1; idx >= 0; --idx)
      this.os.write(this.longBuffer[idx]);
  }

  public void formatCRLF() throws IOException {
    this.os.write('\r');
    this.os.write('\n');
  }

  protected int preformatLong(long value) {
    long next;
    int rest;
    int idx = 0;
    do {
      next = value / 10L;
      rest = (int)(value - (next * 10L));
      this.longBuffer[idx++] = (byte)('0' + rest); // Character.forDigit(rest, 10)
      value = next;
    } while (value > 0L);
    return idx;
  }
}
